<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryRef" :inline="true" :model="queryParams" label-width="68px">
      <el-form-item label="药品名称" prop="medicationName">
        <el-select v-model="queryParams.medicationName" clearable placeholder="请选择药品名称">
          <el-option
              v-for="dict in drug_names"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['inventory:inventory:add']"
            icon="Plus"
            plain
            type="primary"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['inventory:inventory:edit']"
            :disabled="single"
            icon="Edit"
            plain
            type="success"
            @click="handleUpdate"
        >编辑
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['inventory:inventory:remove']"
            :disabled="multiple"
            icon="Delete"
            plain
            type="danger"
            @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['inventory:inventory:export']"
            icon="Download"
            plain
            type="warning"
            @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inventoryList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
      <el-table-column align="center" label="药品名称" prop="medicationName">
        <template #default="scope">
          <dict-tag :options="drug_names" :value="scope.row.medicationName"/>
        </template>
      </el-table-column>
      <el-table-column :formatter="formatquantity" align="center" label="药品个数" prop="quantity"/>
      <el-table-column align="center" label="单位" prop="unit"/>
      <el-table-column :formatter="formatTotalValue" align="center" label="单价" prop="pricePerUnit"/>
      <el-table-column :formatter="formatTotalValue" align="center" label="补货金额" prop="totalValue"/>
      <el-table-column align="center" label="说明" prop="info"/>
      <el-table-column align="center" label="最后修改时间" prop="lastModified" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastModified, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template #default="scope">
          <el-button v-hasPermi="['inventory:inventory:edit']" icon="Edit" link type="primary"
                     @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button v-hasPermi="['inventory:inventory:remove']" icon="Delete" link type="primary"
                     @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        :total="total"
        @pagination="getList"
    />

    <!-- 添加或修改药品库存对话框 -->
    <el-dialog v-model="open" :title="title" append-to-body width="1100px">
      <el-form ref="inventoryRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="药品名称" prop="medicationName">
          <el-select v-model="form.medicationName" placeholder="请选择药品名称">
            <el-option
                v-for="dict in drug_names"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="药品个数" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入药品个数"/>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位"/>
        </el-form-item>
        <el-form-item label="单价" prop="pricePerUnit">
          <el-input v-model="form.pricePerUnit" placeholder="请输入单价"/>
        </el-form-item>
        <el-form-item label="金额" prop="totalValue">
          <el-input v-model="form.totalValue" placeholder="请输入金额"/>
        </el-form-item>
        <el-form-item label="说明" prop="info">
          <el-input v-model="form.info" placeholder="请输入内容" type="textarea"/>
        </el-form-item>
        <el-form-item label="最后修改时间" prop="lastModified">
          <el-date-picker v-model="form.lastModified"
                          clearable
                          placeholder="请选择最后修改时间"
                          type="date"
                          value-format="YYYY-MM-DD">
          </el-date-picker>
        </el-form-item>
        <el-divider content-position="center">用药记录信息表</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button icon="Plus" type="primary" @click="handleAddMedicationUsage">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="Delete" type="danger" @click="handleDeleteMedicationUsage">删除</el-button>
          </el-col>
        </el-row>
        <el-table ref="medicationUsage" :data="medicationUsageList"
                  :row-class-name="rowMedicationUsageIndex" @selection-change="handleMedicationUsageSelectionChange">
          <el-table-column align="center" type="selection" width="50"/>
          <el-table-column align="center" label="序号" prop="index" width="50"/>
          <el-table-column label="药品名称" prop="medicationName" width="170">
            <template #default="scope">
              <el-select v-model="scope.row.medicationName" placeholder="请选择药品名称">
                <el-option
                    v-for="dict in drug_names"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="药品个数" prop="quantityUsed" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.quantityUsed" placeholder="请输入个数"/>
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="unit" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.unit" placeholder="请输入单位"/>
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="pricePerUnit" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.pricePerUnit" placeholder="请输入单价"/>
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="amountSpent" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.amountSpent" placeholder="请输入金额"/>
            </template>
          </el-table-column>
          <el-table-column label="用药日期" prop="usageDate" width="150">
            <template #default="scope">
              <el-date-picker v-model="scope.row.usageDate"
                              clearable
                              placeholder="请选择用药日期"
                              type="date"
                              value-format="YYYY-MM-DD">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="操作说明" prop="operationDescription" width="310">
            <template #default="scope">
              <el-input v-model="scope.row.operationDescription" placeholder="请输入操作说明"/>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script name="Inventory" setup>
import {addInventory, delInventory, getInventory, listInventory, updateInventory} from "@/api/inventory/inventory";

const {proxy} = getCurrentInstance();
const {drug_names} = proxy.useDict('drug_names');

const inventoryList = ref([]);
const medicationUsageList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedMedicationUsage = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const formatTotalValue = (row, column, cellValue) => {
  return `${cellValue} 元`;
}
const formatquantity = (row, column, cellValue) => {
  return `${cellValue} 个`;
}
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    medicationName: null,
  },
  rules: {
    medicationName: [
      {required: true, message: "药品名称不能为空", trigger: "change"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询药品库存列表 */
function getList() {
  loading.value = true;
  listInventory(queryParams.value).then(response => {
    inventoryList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    medicationName: null,
    quantity: null,
    unit: null,
    pricePerUnit: null,
    totalValue: null,
    info: null,
    lastModified: null
  };
  medicationUsageList.value = [];
  proxy.resetForm("inventoryRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加药品库存";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getInventory(_id).then(response => {
    form.value = response.data;
    medicationUsageList.value = response.data.medicationUsageList;
    open.value = true;
    title.value = "修改药品库存";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["inventoryRef"].validate(valid => {
    if (valid) {
      form.value.medicationUsageList = medicationUsageList.value;
      if (form.value.id != null) {
        updateInventory(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addInventory(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除药品库存编号为"' + _ids + '"的数据项？').then(function () {
    return delInventory(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 用药记录序号 */
function rowMedicationUsageIndex({row, rowIndex}) {
  row.index = rowIndex + 1;
}

/** 用药记录添加按钮操作 */
function handleAddMedicationUsage() {
  let obj = {};
  obj.medicationName = "";
  obj.quantityUsed = "";
  obj.unit = "";
  obj.pricePerUnit = "";
  obj.amountSpent = "";
  obj.usageDate = "";
  obj.operationDescription = "";
  medicationUsageList.value.push(obj);
}

/** 用药记录删除按钮操作 */
function handleDeleteMedicationUsage() {
  if (checkedMedicationUsage.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的用药记录数据");
  } else {
    const medicationUsages = medicationUsageList.value;
    const checkedMedicationUsages = checkedMedicationUsage.value;
    medicationUsageList.value = medicationUsages.filter(function (item) {
      return checkedMedicationUsages.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleMedicationUsageSelectionChange(selection) {
  checkedMedicationUsage.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('inventory/inventory/export', {
    ...queryParams.value
  }, `inventory_${new Date().getTime()}.xlsx`)
}

getList();
</script>
